<template>
  <div>
    <el-dialog center title="修改资料" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="个人邮箱">
          <el-input v-model="form.email" autocomplete="off" placeholder="请输入您的个人邮箱"></el-input>
        </el-form-item>
        <el-form-item label="工作邮箱" prop="email_work">
          <el-input v-model="form.email_work" autocomplete="off" placeholder="请输入您的工作邮箱"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm" v-no-more-click:3000>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { updateUser, getMy } from "~/api/user";
import aes from "~/util/aes.js";
export default {
  data() {
    return {
      dialogFormVisible: false,
      form: {},
      rules: {}
    };
  },
  created() {},
  methods: {
    showDialog() {
      this.dialogFormVisible = true;
      this.getInfo();
    },

    getInfo() {
      let userObj = this.$store.state.user;
      this.form = {
        name: userObj.name,
        email: userObj.email,
        email_work: userObj.email_work
      };
    },

    //提交工作邮箱
    submitForm() {
      if (this.$store.state.user.role_id == 2) {
        if (this.form.email_work == "") {
          this.$message.error("工作邮箱不能为空");
          return;
        } else {
          if (
            !/^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/.test(
              this.form.email_work
            )
          ) {
            this.$message.error("请输入正确邮箱");
            return;
          }
        }
        if (this.form.name == "") {
          this.$message.error("用户名不能为空");
          return;
        }
      }
      updateUser(this.$axios, this.form)
        .then(({ data }) => {
          if (data.status == "success") {
            this.$message.success("工作邮箱修改成功");
            //然后再存

            let userData = this.$store.state.user;
            userData.name = this.form.name;
            userData.email = this.form.email;
            userData.email_work = this.form.email_work;

            //修改后先清空cookie
            this.$store.commit("delUser");
            this.$cookies.remove("user");

            this.$cookies.set("user", aes.Encrypt(JSON.stringify(userData)));
            this.$store.commit("setUser", userData);
            this.handleClose();
          } else {
            this.$message.error(data.message);
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    handleClose() {
      this.form = {};
      this.dialogFormVisible = false;
    }
  }
};
</script>
